<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img alt="logo" :width="26" src="@/assets/logo.png"/>
        <a-typography-title :style="{ margin: 0 }" :heading="5">
          GinMeta-Admin
        </a-typography-title>
        <icon-menu-fold v-if="appStore.device === 'mobile'" style="font-size: 22px; cursor: pointer"
                        @click="toggleDrawerMenu"/>
      </a-space>
    </div>
    <ul class="right-side">
      <li>
        <a-tooltip :content="theme === 'light' ? '黑暗模式' : '明亮模式'">
          <a-button class="nav-btn" type="outline" :shape="'circle'" @click="handleToggleTheme">
            <template #icon>
              <icon-moon-fill v-if="theme !== 'dark'"/>
              <icon-sun-fill v-else/>
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-dropdown trigger="click">
          <a-avatar :size="32" :style="{ marginRight: '8px', cursor: 'pointer' }">
            <img v-if="avatar !== ''" alt="avatar" :src="avatar"/>
            <span v-else>A</span>
          </a-avatar>
          <template #content>
            <a-doption>
              <a-space @click="handleUserInfo">
                <icon-user/>
                <span>个人中心</span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleEditPassword">
                <icon-edit/>
                <span>修改密码</span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export/>
                <span>退出登陆</span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>

    <a-modal v-model:visible="formModelSetting.visible" :title="formModelSetting.title"
             :ok-text="formModelSetting.okTest" :mask-closable="false" @cancel="handleCancel"
             @before-ok="modelBeforeOkBut" @ok="handleOk">
      <a-space class="modal-avatar" direction="vertical" :style="{ width: '100%' }">
        <a-upload :file-list="file ? [file] : []" :show-file-list="false" :custom-request="customUpload"
                  @success="handleSuccess">
          <template #upload-button>
            <div
                :class="`arco-upload-list-item${file && file.status === 'error' ? ' arco-upload-list-item-error' : ''}`">
              <div v-if="file && file.url" class="arco-upload-list-picture custom-upload-avatar">
                <img :src="file.url" alt=""/>
                <div class="arco-upload-list-picture-mask">
                  <IconEdit/>
                </div>
                <a-progress
                    v-if="file.status === 'uploading' && file.percent < 100"
                    :percent="file.percent"
                    type="circle"
                    size="mini"
                    :style="{position: 'absolute',left: '50%',top: '50%',transform: 'translateX(-50%) translateY(-50%)',}"
                />
              </div>
              <div v-else class="arco-upload-picture-card">
                <div class="arco-upload-picture-card-text">
                  <IconPlus/>
                  <div style="margin-top: 10px; font-weight: 600">头像上传</div>
                </div>
              </div>
            </div>
          </template>
        </a-upload>
      </a-space>
      <a-form ref="formRef" :model="userInfo">
        <a-form-item field="username" label="用户名" :rules="[{required:true,message:'用户名不能为空'}]">
          <a-input v-model="userInfo.username" readonly/>
        </a-form-item>
        <a-form-item field="nickName" label="昵称" :rules="[{required:true,message:'昵称不能为空'}]">
          <a-input v-model="userInfo.nickName" placeholder="请输入昵称" max-length="10" show-word-limit/>
        </a-form-item>
        <a-form-item field="gender" label="性别">
          <a-radio-group v-model="userInfo.gender">
            <a-radio value="M">男</a-radio>
            <a-radio value="F">女</a-radio>
            <a-radio value="N" disabled>隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="phone" label="手机号">
          <a-input v-model="userInfo.phone" placeholder="请输入手机号" max-length="11" show-word-limit/>
        </a-form-item>
        <a-form-item field="email" label="邮箱">
          <a-input v-model="userInfo.email" placeholder="请输入邮箱" max-length="16" show-word-limit/>
        </a-form-item>
      </a-form>
    </a-modal>

    <!--  修改密码  -->
    <a-modal ref="modalRefPwd" v-model:visible="modelSettingPwd.visible"
             :title="modelSettingPwd.title"
             :ok-text="modelSettingPwd.okText"
             :mask-closable="false"
             @cancel="handleCancelPwd"
             @before-ok="handleBeforeOkPwd"
             @ok="handleOkPwd">
      <a-form ref="formDataRefPwd" :model="formDataPwd">
        <a-form-item field="oldPassword" label="旧密码"
                     :rules="[{required:true, message:'旧密码不能为空', type: 'string'}]">
          <a-input v-model="formDataPwd.oldPassword" placeholder="请输入旧密码" max-length="16" show-word-limit/>
        </a-form-item>
        <a-form-item field="newPassword" label="新密码"
                     :rules="[{required:true, message:'新密码不能为空', type: 'string'}]">
          <a-input v-model="formDataPwd.newPassword" placeholder="请输入新密码" max-length="16" show-word-limit/>
        </a-form-item>
        <a-form-item field="confirmPassword" label="确认密码"
                     :rules="[{required:true, message:'确认密码不能为空', type: 'string'}]">
          <a-input v-model="formDataPwd.confirmPassword" placeholder="请再次输入新密码" max-length="16"
                   show-word-limit/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {computed, inject, reactive, ref} from 'vue';
import {Message} from '@arco-design/web-vue';
import {useDark, useToggle} from '@vueuse/core';
import {useAppStore, useUserStore} from '@/store';
import useUser from '@/hooks/user';
import {editInfo, editPwd, EditPwdParams, editUserInfoParams, uploadAvatar} from '@/api/system/user';
import {useRouter} from 'vue-router';

const router = useRouter();
const appStore = useAppStore();
const userStore = useUserStore();
const {logout} = useUser();
const file = ref();
const formRef = ref();
const avatar = computed(() => {
  if (userStore.avatar === '') {
    return userStore.avatar;
  }
  return import.meta.env.VITE_API_BASE_URL + userStore.avatar;
});
const userInfo = reactive({
  userId: userStore.userId,
  avatar: import.meta.env.VITE_API_BASE_URL + userStore.avatar,
  username: userStore.username,
  nickName: userStore.nickName,
  phone: userStore.phone,
  email: userStore.email,
  gender: userStore.gender,
});
const fileInfo = reactive({
  uid: '',
  name: '',
  url: '',
});
// 退出登陆
const handleLogout = () => {
  logout();
};
// 折叠菜单按钮
const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;
const theme = computed(() => {
  return appStore.theme;
});
const isDark = useDark({
  selector: 'body',
  attribute: 'arco-theme',
  valueDark: 'dark',
  valueLight: 'light',
  storageKey: 'arco-theme',
  onChanged(dark: boolean) {
    // overridden default behavior
    appStore.toggleTheme(dark);
  },
});
const toggleTheme = useToggle(isDark);
const handleToggleTheme = () => {
  toggleTheme();
};

// 对话框是否展示
const formModelSetting = reactive({
  visible: false,
  onLoading: false,
  title: "个人信息",
  okTest: "修改",
});
// 个人信息按钮
const handleUserInfo = () => {
  // 打开弹窗
  formModelSetting.visible = true;
  // 回显头像
  if (userStore.avatar !== '') {
    fileInfo.url = import.meta.env.VITE_API_BASE_URL + userStore.avatar;
    file.value = fileInfo;
  }
};
// 表单确定创建之前执行
const modelBeforeOkBut = async () => {
  let flag = true;
  // 提交表单
  await formRef.value.validate().then((res: any) => {
    if (res !== undefined) {
      flag = false;
      formModelSetting.visible = true;
      formModelSetting.onLoading = false;
    }
  });
  return flag;
};
// 弹窗确认按钮
const handleOk = async () => {
  const params: editUserInfoParams = userInfo;
  const res = await editInfo(params);
  // @ts-ignore
  if (res.code === 200) {
    Message.success({
      content: '修改成功',
      duration: 2 * 1000,
    });
    // 关闭弹窗
    formModelSetting.visible = false;
    // 重置头像
    fileInfo.url = '';
  } else {
    // 不关闭弹窗
    formModelSetting.visible = true;
  }
};
// 弹窗取消按钮
const handleCancel = () => {
  // 关闭弹窗
  formModelSetting.visible = false;
  // 重置头像
  fileInfo.url = '';
};

// 头像自定义上传
const customUpload = async (option: any) => {
  const formData = new FormData();
  formData.append("avatarFile", option.fileItem.file);
  const res = await uploadAvatar(formData);
  // @ts-ignore
  if (res.code === 200 && res.data) {
    option.onSuccess(option.fileItem.file);
    // 更新头像缓存
    userStore.avatar = res.data;
  }
};
// 上传成功
const handleSuccess = (currentFile: any) => {
  file.value = {
    ...currentFile,
  };
};

/* 修改密码 - start */
const modalRefPwd = ref();
const formDataRefPwd = ref();

// 表单
const formDataPwd = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 重置表单
const resetFormDataPwd = async () => {
  formDataPwd.oldPassword = '';
  formDataPwd.newPassword = '';
  formDataPwd.confirmPassword = '';
  formDataRefPwd.value.clearValidate();
}

// 对话框
const modelSettingPwd = reactive({
  visible: false,
  onLoading: false,
  title: '',
  okText: '',
  cancelText: ''
})

// 修改密码按钮
const handleEditPassword = async () => {
  // 重置表单
  await resetFormDataPwd();
  // 打开对话框
  modelSettingPwd.title = '修改密码';
  modelSettingPwd.visible = true;
}

// 取消对话框按钮
const handleCancelPwd = () => {
  // 重置表单
  resetFormDataPwd();
  // 关闭对话框
  modelSettingPwd.title = '';
  modelSettingPwd.visible = false;
  modelSettingPwd.onLoading = false;
}

// 确定对话框之前
const handleBeforeOkPwd = async () => {
  let flag = true;
  // 提交表单
  await formDataRefPwd.value.validate().then((res: any) => {
    if (res !== undefined) {
      flag = false;
    }
  });
  if (formDataPwd.newPassword !== formDataPwd.confirmPassword) {
    Message.warning({
      content: '两次密码输入不一致',
      duration: 2 * 1000
    });
    formDataRefPwd.value.setFields({
      newPassword: {
        status: 'error',
        message: '两次密码输入不一致'
      },
      confirmPassword: {
        status: 'error',
        message: '两次密码输入不一致'
      }
    });
    flag = false;
  }
  return flag;
}

// 确定对话框按钮
const handleOkPwd = async () => {
  const params: EditPwdParams = {
    oldPassword: formDataPwd.oldPassword,
    newPassword: formDataPwd.newPassword,
  }
  const {code}: any = await editPwd(params);
  if (code === 200) {
    Message.success({
      content: '修改密码成功，请重新登录！',
      duration: 2 * 1000
    });
    await userStore.logout();
    const currentRoute = router.currentRoute.value;
    await router.push({
      name: 'login',
      query: {
        ...router.currentRoute.value.query,
        redirect: currentRoute.name as string,
      },
    });
  }
  // 重置表单
  await resetFormDataPwd();
  // 关闭对话框
  modelSettingPwd.title = '';
  modelSettingPwd.visible = false;
  modelSettingPwd.onLoading = false;
}
/* 修改密码 - end */
</script>

<style scoped lang="less">
.navbar {
  display: flex;
  justify-content: space-between;
  height: 100%;
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
}

.left-side {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.right-side {
  display: flex;
  padding-right: 20px;
  list-style: none;

  :deep(.locale-select) {
    border-radius: 20px;
  }

  li {
    display: flex;
    align-items: center;
    padding: 0 10px;
  }

  a {
    color: var(--color-text-1);
    text-decoration: none;
  }

  .nav-btn {
    border-color: rgb(var(--gray-2));
    color: rgb(var(--gray-8));
    font-size: 16px;
  }

  .trigger-btn,
  .ref-btn {
    position: absolute;
    bottom: 14px;
  }

  .trigger-btn {
    margin-left: 14px;
  }
}
</style>

<style lang="less">
.message-popover {
  .arco-popover-content {
    margin-top: 0;
  }
}

.modal-avatar {
  text-align: center;
  margin-bottom: 20px;
}
</style>
